//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

use git2::{Error, Repository};
use serde::Serialize;
use std::path::PathBuf;

#[derive(Serialize)]
struct TagInfo {
    name: String,
    commit_id: String,
    commit_summary: String,
    commit_time: i64,
}

pub fn exec(git_path: PathBuf) -> Result<(), Error> {
    let repo = Repository::open(git_path);
    if repo.is_err() {
        return Err(repo.err().unwrap());
    }
    let repo = repo.unwrap();

    let mut info_list = Vec::new();
    let result = repo.tag_foreach(|oid, name| {
        let obj = repo.find_object(oid, None);
        if obj.is_err() {
            return true;
        }
        let obj = obj.unwrap();
        let commit = obj.peel_to_commit();
        if commit.is_err() {
            return true;
        }
        let commit = commit.unwrap();

        info_list.push(TagInfo {
            name: String::from_utf8_lossy(name).to_string(),
            commit_id: commit.id().to_string(),
            commit_summary: String::from(commit.message().unwrap_or_default()),
            commit_time: commit.time().seconds() * 1000,
        });
        return true;
    });
    if result.is_err() {
        return Err(result.err().unwrap());
    }
    println!("{}", serde_json::to_string(&info_list).unwrap());
    return Ok(());
}
